<?php

/**
 * article actions.
 *
 * @package    jiazhang
 * @subpackage article
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class articleActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
        $tag = trim($request->getParameter('tag',''));
        
        if(strlen($tag) == 0 || $tag == '最新'){
            $this->getResponse()->setTitle('文章 - 壹童学');
            $dql = Doctrine::getTable('Article')->createQuery()->where('display = 1')->orderBy('created_at desc'); 
        }else{
            $this->getResponse()->setTitle($tag.'文章 - 壹童学 - ');
            $article_ids = Doctrine::getTable('ArticleTag')->createQuery()->where('tag = ?',$tag)->execute()->toKeyValueArray('article_id', 'article_id');
            
            if(count($article_ids) == 0){
                $dql = Doctrine::getTable('Article')->createQuery()->where('id = 0'); 
            }else{
                $dql = Doctrine::getTable('Article')->createQuery()->where('display = 1')->andWhereIn('id',$article_ids)->orderBy('created_at desc'); 
            }
        }

        $page = $request->getParameter('page',1);
        $this->pager = new sfDoctrinePager('Article',15);
        $this->pager->setQuery($dql);
        $this->pager->setPage($page);
        $this->pager->init();
  }
  
  public function executeShow(sfWebRequest $request){
      $this->forward404Unless($this->article = Doctrine::getTable('Article')->findOneById($id = $request->getParameter('id',0)));
      $this->getResponse()->setTitle($this->article->getTitle().' - 文章 - 壹童学');
      if($this->article->getDisplay() != 1) $this->redirect ('@homepage');
      $article_attr = Doctrine::getTable('ArticleAttribute')->findOneByArticleId($id);
      $article_attr->incrementClick()->save();
      $this->comments = Doctrine::getTable('ArticleComment')->createQuery()->where('display = ?',1)->andWhere('article_id = ?',$id)->orderBy('created_at desc')->execute();
  }
  
  public function executeComment(sfWebRequest $request){
      $article_id = (int)$request->getParameter('article_id');
      $user_id = $this->getUser()->getAttribute('user_id');
      
      if($request->isMethod('post')){
        if($this->getUser()->isAuthenticated()){
            $content = $request->getParameter('content','');
            $comment = new ArticleComment();
            $comment->setUserId($user_id)->setArticleId($article_id)->setContent($content)->save();
            $this->getUser()->setFlash('success', '评论发布成功！');
            $this->redirect('article/show?id='.$article_id);
        }else{
            $this->getUser()->setFlash('error', '请先登入！');
            $this->redirect('article/show?id='.$article_id);
            return $this->renderText('请先登入！');
        }
      }
  }
  
}
